package com.dushuren.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.dushuren.project.common.BaseResponse;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.common.ResultUtils;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.model.dto.*;
import com.dushuren.project.model.entity.User;
import com.dushuren.project.model.vo.UserVo;
import com.dushuren.project.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

import static com.dushuren.project.constant.UserConstant.USER_LOGIN_STATE;

/**
 * 用户接口
 * @author dushuren
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:8000", allowCredentials = "true")
public class UserController {

  @Resource
  UserService userService;

  /***
   * 用户注册
   */
  @PostMapping("/register")
  public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
    if (userRegisterRequest == null) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    String userAccount = userRegisterRequest.getUserAccount();
    String userPassword = userRegisterRequest.getUserPassword();
    String checkPassword = userRegisterRequest.getCheckPassword();
    if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    long result = userService.userRegister(userAccount, userPassword, checkPassword);
    return ResultUtils.success(result);
  }

  /***
   * 用户登入
   */
  @PostMapping("/login")
  public BaseResponse<UserVo> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){
    if (userLoginRequest == null) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    String userAccount = userLoginRequest.getUserAccount();
    String userPassword = userLoginRequest.getUserPassword();
    if (StringUtils.isAnyBlank(userAccount,userPassword)) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    UserVo userVO = userService.userLogin(userAccount, userPassword, request);
    return ResultUtils.success(userVO);
  }

  /***
   * 用户注销
   */
  @PostMapping("/logout")
  public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
    boolean result = userService.userLogout(request);
    return ResultUtils.success(result);
  }

  /***
   * 获取当前登录用户 , 重缓存中取出用户信息 ，如果缓存中没有，则要求重新登录
   */
  @GetMapping("/get/login")
  public BaseResponse<UserVo> getLoginUser(HttpServletRequest request) {
//    User user = userService.getLoginUser(request);
    UserVo userVO = userService.getIsServletRequest(request);
    return ResultUtils.success(userVO);
  }


  // User CDUS

  /***
   * 获取个人用户信息
   */
  @GetMapping("/get")
  public BaseResponse<UserVo> getUser(UserGetRequest userGetId, HttpServletRequest request) {
    User user = userService.getUser(userGetId);
    UserVo resultUser = userService.getSftUser(user);
    return ResultUtils.success(resultUser);
  }

  /***
   * 获取用户列表
   */
  @GetMapping("/list")
  public BaseResponse<List<UserVo>> listUser(UserQueryRequest userQueryRequest, HttpServletRequest request) {
    userService.getLoginUser(request);

      if (userQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    User userQuery = new User();
    BeanUtils.copyProperties(userQueryRequest,userQuery);
    /*
     * 这里直接将 userQuery 直接载入 QueryWrapper中 能直接进行 条件判断
     */
    QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);

    queryWrapper.select("id", "userAccount", "userPassword", "userName", "avatarUrl", "gender", "userProfile", "userProfileState"
    , "phone", "email", "userStatus", "tags", "creditsNum", "createTime", "updateTime");
    List<User> userList = userService.list(queryWrapper);
    List<UserVo> userVoList = userList.stream().map(user -> userService.getSftUser(user)).collect(Collectors.toList());
    return ResultUtils.success(userVoList);
  }


  /***
   * 增加用户
   */
  @PostMapping("/add")
  public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest, HttpServletRequest request){
    if (userService.getLoginUser(request) == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    String userPassword = userAddRequest.getUserPassword();
    String userAccount = userAddRequest.getUserAccount();
    if (userAccount.length() < 4) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户长度过短");
    }
    if (userPassword.length() < 8 ) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
    }
    if (StringUtils.isAnyBlank(userAccount, userPassword)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR, "请输入完全");
    }
    User user = new User();
    user.setUserPassword(DigestUtils.md5DigestAsHex(("dushuren" + userPassword).getBytes()));
    BeanUtils.copyProperties(userAddRequest, user);
    boolean save = userService.save(user);
    if (!save) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    return ResultUtils.success(user.getId());
  }


  /***
   *管理员接口 更新用户信息
   */
  @PostMapping("/update")
  public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest, HttpServletRequest request){
    if (userService.getLoginUser(request) == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    if (userUpdateRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }

    User user = new User();
    BeanUtils.copyProperties(userUpdateRequest, user);
    boolean result = userService.updateById(user);
    return ResultUtils.success(result);
  }

  /***
   * 管理员 分页获取用户信息
   */
  @GetMapping("/list/page")
  public BaseResponse<Page<UserVo>> listUserByPage(UserQueryRequest userQueryRequest, HttpServletRequest request) {
    if (userService.getLoginUser(request) == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }
    long current = 1;
    long size = 10;
    User userQuery = new User();
    if (userQueryRequest != null) {
      BeanUtils.copyProperties(userQueryRequest, userQuery);
      current = userQueryRequest.getCurrent();
      size = userQueryRequest.getPageSize();
    }
    QueryWrapper<User> queryWrapper = new QueryWrapper<>(userQuery);
    Page<User> userPage = userService.page(new Page<>(current,size), queryWrapper);
    Page<UserVo>  userVOPage = new PageDTO<>(userPage.getCurrent(), userPage.getSize(), userPage.getTotal());
    List<UserVo> userVoList = userPage.getRecords().stream().map(user -> {
      UserVo userVO = new UserVo();
      BeanUtils.copyProperties(user,userVO);
      return userVO;
    }).collect(Collectors.toList());
    userVOPage.setRecords(userVoList);
    return ResultUtils.success(userVOPage);
  }

  /***
   * 管理员 删除用户
   */
  @PostMapping("/delete")
  public BaseResponse<Boolean> deleteUser(UserDeleteRequest userDeleteRequest, HttpServletRequest request){
    if (userService.getLoginUser(request) == null) {
      throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
    }

    if (userDeleteRequest == null || userDeleteRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean resultDelete = userService.removeById(userDeleteRequest.getId());
    return ResultUtils.success(resultDelete);
  }

  /***
   *  用户 更新(修改)个人信息
   */
  @PostMapping("/renew/user")
  public BaseResponse<Long> renewUser(@RequestBody UserRenewRequest renewRequest, HttpServletRequest request) {
    // 校验更新数据是否存在
    if (renewRequest == null ||renewRequest.getId() <= 0 ) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    if (!StringUtils.isNotBlank(renewRequest.getUserName())) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Integer gender = renewRequest.getGender();
    if (gender < 0 || gender > 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    // 校验登入态是否存在
    UserVo userVo = userService.getIsServletRequest(request);
    // 更新数据校验 不更新重复数据 返回 0 更新成功 1 更新的未修改
    Long result =  userService.renewUser(renewRequest, userVo);

    return ResultUtils.success(result);
  }
}
